package com.uxsino.authority.lib.aop;

import com.uxsino.authority.lib.annotation.Permission;
import com.uxsino.authority.lib.handler.AuthorityHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 权限检查的aop
 * @Author: jane
 * @Date: 2019/8/30 13:59
 */
@Aspect
@Component
public class PermissionAop {

    @Autowired
    private AuthorityHandler checkService;

    @Pointcut(value = "@annotation(com.uxsino.authority.lib.annotation.Permission)")
    private void cutPermission() {

    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point) throws Throwable {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();

        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Permission permission = method.getAnnotation(Permission.class);
        String[] value = permission.value();
        String[] permissions = permission.permission();
        if (permissions.length > 0) {
            boolean result = checkService.checkMenuPermission(session, value, permissions);
            if (result) {
                return point.proceed();
            } else {
                throw new NoPermissionException();
            }
        } else {
            return point.proceed();
        }

    }

}
